package com.imooc.course.system.controller.admin;

import com.imooc.course.system.form.RoleForm;
import com.imooc.course.system.form.PageForm;
import com.imooc.course.server.dto.RoleDto;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.dto.ResponseDto;
import com.imooc.course.server.service.RoleService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/admin/role")
public class RoleController {

    private static final Logger log = LoggerFactory.getLogger(RoleController.class);
    public static final String BUSINESS_NAME = "角色";


    @Resource(name = "roleService")
    private RoleService roleService;

    /**
     * 查询列表
     * @param pageForm 传入的page和size
     * @return
     */
    @PostMapping("/list")
    public ResponseDto getList(@RequestBody PageForm pageForm) {
        PageDto pageDto = CopyUtil.copy(pageForm, PageDto.class);
        roleService.getList(pageDto);
        return ResponseDto.success().setContent(pageDto);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param roleForm
     * @return
     */
    @PostMapping("/save")
    public ResponseDto addRole(@RequestBody RoleForm roleForm) {
        //入参检查
        ValidatorUtil.notNull(roleForm.getName(), "角色");
        ValidatorUtil.minimumToMaximum(roleForm.getName(), "角色", 1, 50);
        ValidatorUtil.notNull(roleForm.getDesc(), "描述");
        ValidatorUtil.minimumToMaximum(roleForm.getDesc(), "描述", 1, 100);

        RoleDto roleDto = CopyUtil.copy(roleForm, RoleDto.class);
        roleService.save(roleDto);
        return ResponseDto.success().setContent(roleDto);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResponseDto del(@PathVariable String id) {
        roleService.delete(id);
        return ResponseDto.success();
    }
}
